<template>
  <div id="app-container">
    <div id="log-container" class="log-container">
      <p v-html ="msg"/>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      stompClient: '',
      timer: '',
      msg: ''
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
    this.initWebSocket()
  },
  beforeDestroy: function() {
    // 页面离开时断开连接,清除定时器
    this.disconnect()
    clearInterval(this.timer)
  },
  methods: {
    initWebSocket() {
      this.connection()
      const that = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send('test')
        } catch (err) {
          console.log('断线了: ' + err)
          that.connection()
        }
      }, 5000)
    },
    connection() {
      // 建立连接对象
      const socket = new SockJS(this.baseApi + '/websocket')
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket)
      // 定义客户端的认证信息,按需求配置
      const headers = {
        'Authorization': 'Bearer ' + getToken()
      }
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, () => {
        this.stompClient.subscribe('/topic/consolelog', (event) => { // 订阅服务端提供的某个topic
          console.log(event) // msg.body存放的是服务端发送给我们的信息
          var content = JSON.parse(event.body)
          const level = content.level
          let levelStyle = '<span>' + level + '</span>'
          if (level === 'INFO') {
            levelStyle = '<span style="color: rgb(54,165,141);">' + level + '</span>'
          }
          if (level === 'WARN') {
            levelStyle = ' <span style="color: rgb(247,197,124);">' + level + '</span>'
          }
          if (level === 'ERROR') {
            levelStyle = '<span style="color: rgb(206,71,58);">' + level + '</span>'
          }
          this.msg = this.msg + levelStyle + '&nbsp;&nbsp;&nbsp;' +
            '<span style="color: rgb(57,111,140);">' + content.timestamp + '</span>' +
            '&nbsp;&nbsp;&nbsp;' +
            '<span style="color: rgb(167,168,39);">' + content.threadName + '</span>' +
            '&nbsp;&nbsp;&nbsp;' +
            '<span style="color: rgb(174,138,190);">' + content.className + '</span>' +
          '&nbsp;&nbsp;&nbsp;' +
            '<span style="color: rgb(210,213,219);">' + content.body + '</span><br>'
        }, headers)
      }, (err) => {
        // 连接发生错误时的处理函数
        console.log('失败')
        console.log(err)
      })
    }, // 连接 后台
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    }// 断开连接
  }
}

</script>
<style>
  .log-container{
    width: 100%;
    height: 750px;
    overflow-y: scroll;
    background: #0f1521;
    color: #aaaaaa;
    padding: 10px;
  }
</style>
